/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Data;

import HangHoa.*;
import HoaDon.XuatNhap;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Scanner;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextField;
import javax.swing.ListModel;

/**
 *
 * @author Tuan
 */
public class DataManager {

    public static final String FOLDER = "DuLieu";
    public static final String FILENAMEDATA = "Database.txt";
    public static final String FILENAMENHAP = "NHAPHANG.txt";
    public static final String FILENAMEBAN = "BANHANG.txt";
    public static final String FILENAMEKH = "KHACHHANG.txt";
    public static final String FILEPATHDATA = FOLDER + File.separator + FILENAMEDATA;
    public static final String FILEPATHNHAP = FOLDER + File.separator + FILENAMENHAP;
    public static final String FILEPATHBAN = FOLDER + File.separator + FILENAMEBAN;
    public static final String FILEPATHKH = FOLDER + File.separator + FILENAMEKH;

    public static Vector<SanPham> getDSData() throws IOException {
        Vector<SanPham> vT = new Vector<SanPham>();
        try {
            FileInputStream Data = new FileInputStream(FILEPATHDATA);
            Scanner input = new Scanner(Data, "UTF-8");
            while (input.hasNextLine()) {
                String info[] = input.nextLine().replace("\ufeff", "").split(";");
                vT.add(convertToSP(info));
            }
            Data.close();
            input.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        }

        return vT;
    }

    public static SanPham convertToSP(String str[]) {
        if (str[0].startsWith("QUAN")) {
            Quan Q = new Quan(str);
            return (SanPham) Q;
        } else if (str[0].startsWith("AO")) {
            Ao A = new Ao(str);
            return (SanPham) A;
        } else if (str[0].startsWith("GIAY")) {
            Giay G = new Giay(str);
            return (SanPham) G;
        }
        return null;
    }

    public static String[] searchData(String maHH) {
        String sPre[] = null;
        try {
            FileInputStream Data = new FileInputStream(FILEPATHDATA);
            Scanner input = new Scanner(Data, "UTF-8");
            while (input.hasNextLine()) {
                String sP[] = input.nextLine().split(";");
                if (sP[0].replace("\ufeff", "").startsWith(maHH)) {
                    sPre = sP;
                }
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return sPre;
    }

    public static void saveToData(Vector<String[]> allSP) {
        try {
            FileOutputStream fos = new FileOutputStream(FILEPATHDATA, false);
            PrintWriter pw = new PrintWriter(fos);
            for (int i = 0; i < allSP.size(); i++) {
                for (int j = 0; j < allSP.get(i).length; j++) {
                    pw.print(allSP.get(i)[j] + ";");
                }
                pw.println();
            }
            pw.close();
            fos.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static String getMaNhap() {
        try {
            FileInputStream data = new FileInputStream(FILEPATHNHAP);
            Scanner input = new Scanner(data, "UTF-8");
            String nhap[] = null;
            while (input.hasNext()) {
                nhap = input.nextLine().split(";");
            }
            input.close();
            data.close();
            if (nhap != null) {
                return nhap[0].replace("\ufeff", "");
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public static String getMaNhap(String maCu) {
        if (maCu != null) {
            maCu = "" + (Integer.parseInt(maCu.replace("N", "")) + 1);
            while (maCu.length() < 3) {
                maCu = "0" + maCu;
            }

            return ("N" + maCu);
        } else {
            return "N001";
        }
    }

    public static String getMaBan() {
        try {
            FileInputStream data = new FileInputStream(FILEPATHBAN);
            Scanner input = new Scanner(data, "UTF-8");
            String ban[] = null;
            while (input.hasNext()) {
                ban = input.nextLine().split(";");
            }
            input.close();
            data.close();
            if (ban != null) {
                return ban[0].replace("\ufeff", "");
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public static String getMaBan(String maCu) {
        if (maCu != null) {
            maCu = "" + (Integer.parseInt(maCu.replace("B", "")) + 1);
            while (maCu.length() < 3) {
                maCu = "0" + maCu;
            }

            return ("B" + maCu);
        } else {
            return "B001";
        }
    }

    public static void updateNhapHang(XuatNhap nhap) {
        String sP[] = searchData(nhap.getMaHH());
        sP[6] = nhap.getSoLuong() + "";
        sP[4] = nhap.getGiaNhap() + "";
        sP[5] = nhap.getGiaBan() + "";
        updateData(sP);
        saveToDataNhap(nhap);
    }

    private static void saveToDataNhap(XuatNhap nhap) {
        Vector<XuatNhap> dataNhap = new Vector();
        if (filterDataNhap("") != null) {
            dataNhap = filterDataNhap("");
        }
        dataNhap.add(nhap);
        try {
            FileOutputStream fos = new FileOutputStream(FILEPATHNHAP, false);
            PrintWriter pw = new PrintWriter(fos);
            for (int i = 0; i < dataNhap.size(); i++) {
                pw.println(dataNhap.get(i).getMaNhap() + ";" + dataNhap.get(i).getNgayGD() + ";" + dataNhap.get(i).getMaHH() + ";" + dataNhap.get(i).getLo() + ";" + dataNhap.get(i).getSoLuong() + ";" + dataNhap.get(i).getGiaNhap() + ";" + dataNhap.get(i).getGiaBan() + ";");
            }
            pw.close();
            fos.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static Vector<XuatNhap> filterDataNhap(String key) {
        Vector<XuatNhap> ketQua = new Vector();
        try {
            FileInputStream data = new FileInputStream(FILEPATHNHAP);
            Scanner input = new Scanner(data, "UTF-8");
            while (input.hasNextLine()) {
                String sP[] = input.nextLine().split(";");
                XuatNhap XN = new XuatNhap();
                if ((sP[2].toLowerCase().contains(key.toLowerCase())) || (key == "")) {
                    XN.setMaNhap(sP[0]);
                    XN.setNgayGD(sP[1]);
                    XN.setMaHH(sP[2]);
                    XN.setLo(Integer.parseInt(sP[3]));
                    XN.setSoLuong(Integer.parseInt(sP[4]));
                    XN.setGiaNhap(Double.parseDouble(sP[5]));
                    XN.setGiaBan(Double.parseDouble(sP[6]));
                    ketQua.add(XN);
                }
            }
            input.close();
            data.close();
            if (ketQua.size() > 0) {
                return ketQua;
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public static Vector<Vector> convertToVector(Vector<XuatNhap> DataNhap) {
        Vector ketQua = new Vector();
        if (DataNhap != null) {
            for (int i = 0; i < DataNhap.size(); i++) {
                Vector one = new Vector();
                one.add("" + DataNhap.get(i).getMaNhap());
                one.add("" + DataNhap.get(i).getNgayGD());
                one.add("" + DataNhap.get(i).getMaHH());
                one.add("" + DataNhap.get(i).getLo());
                one.add("" + DataNhap.get(i).getSoLuong());
                one.add("" + DataNhap.get(i).getGiaNhap());
                one.add("" + DataNhap.get(i).getGiaBan());
                ketQua.add(one);
            }
        }
        return ketQua;

    }

    public static Vector<Vector> toVector(Vector<SanPham> Data) {
        Vector ketQua = new Vector();
        if (Data != null) {
            for (int i = 0; i < Data.size(); i++) {
                ketQua.add(Data.get(i).toVector());
            }
        }
        return ketQua;
    }

    public static void updateData(String[] sSP) {
        Vector<String[]> allSP = new Vector();
        try {
            FileInputStream Data = new FileInputStream(FILEPATHDATA);
            Scanner input = new Scanner(Data, "UTF-8");
            while (input.hasNextLine()) {
                String info[] = input.nextLine().split(";");
                if (info[0].equals(sSP[0])) {
                    allSP.add(sSP);
                } else {
                    allSP.add(info);
                }
            }
            input.close();
            Data.close();
            saveToData(allSP);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void newtoData(String[] sSP) {
        try {
            FileOutputStream Data = new FileOutputStream(FILEPATHDATA, true);
            PrintWriter pw = new PrintWriter(Data);
            for (int i = 0; i < sSP.length; i++) {
                pw.print(sSP[i] + ";");
            }
            pw.println();
            pw.close();
            Data.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static SanPham searchList(Vector<SanPham> vTData, int selectedIndex) {
        int index = 0;
        for (int i = 1; i < vTData.size(); i++) {
            if (vTData.get(i).getsL() > 0) {
                index++;
            }
            if (index == selectedIndex + 1) {
                return vTData.get(i);
            }
        }
        return null;

    }

    public static double tongTien(Vector<Vector> vTHoaDon) {
        double tong = 0;
        for (int i = 0; i < vTHoaDon.size(); i++) {
            tong = tong + Double.parseDouble((String) vTHoaDon.get(i).get(2)) * Integer.parseInt((String) vTHoaDon.get(i).get(3));
        }
        return tong;
    }

    public static void saveToDataHoaDon(Vector<Vector> vTHoaDon, String text) {
        try {
            SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss dd/MM/yyyy");
            FileOutputStream fos = new FileOutputStream(FILEPATHBAN, true);
            PrintWriter pw = new PrintWriter(fos);
            for (int i = 0; i < vTHoaDon.size(); i++) {
                String sP[] = searchData(vTHoaDon.get(i).get(0).toString());
                sP[6] = (Integer.parseInt(sP[6]) - Integer.parseInt(vTHoaDon.get(i).get(3).toString())) + "";
                updateData(sP);
                pw.println(text + ";" + vTHoaDon.get(i).get(0) + ";" + vTHoaDon.get(i).get(1) + ";" + vTHoaDon.get(i).get(2) + ";" + vTHoaDon.get(i).get(3) + ";" + vTHoaDon.get(i).get(4) + ";");
            }
            pw.close();
            fos.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void saveToKhachHang(String text, String text0, String text1) {
        try {
            SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss dd/MM/yyyy");
            FileOutputStream fos = new FileOutputStream(FILEPATHKH, true);
            PrintWriter pw = new PrintWriter(fos);
            pw.println(text + ";" + timeFormat.format(System.currentTimeMillis()) + ";" + text0 + ";" + text1);
            pw.close();
            fos.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        } //To change body of generated methods, choose Tools | Templates.
    }

    public static Vector loadDataBan() {
        Vector<String> vTDataBan = new Vector();
        try {
            FileInputStream dataBan = new FileInputStream(FILEPATHBAN);
            Scanner input = new Scanner(dataBan, "UTF-8");
            while (input.hasNextLine()) {
                String data = input.nextLine();
                vTDataBan.add(data);
            }
            input.close();
            dataBan.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return vTDataBan;
    }

    public static Vector thongKe() {
        Vector<String> vTDataS = loadDataBan();
        Vector<String[]> sTDataBan = new Vector();
        Vector vTDataBan = new Vector();
        for (int i = 0; i < vTDataS.size(); i++) {
            sTDataBan.add(vTDataS.get(i).replace("\ufeff", "").substring(5).split(";"));
        }
        System.out.println("XXX" + sTDataBan.size());
        for (int i = 0; i < sTDataBan.size(); i++) {
            System.out.println("i=" + i);
            for (int j = i + 1; j < sTDataBan.size(); j++) {
                while ((sTDataBan.get(i)[0].toLowerCase().equals(sTDataBan.get(j)[0].toLowerCase()))
                        && (sTDataBan.get(i)[2].equals(sTDataBan.get(j)[2]))) {
                    System.out.println("j=" + j);
                    sTDataBan.get(i)[3] = Integer.parseInt(sTDataBan.get(i)[3]) + Integer.parseInt(sTDataBan.get(j)[3]) + "";
                    sTDataBan.removeElementAt(j);
                    System.out.println("XXX" + sTDataBan.size());
                    if (j >= sTDataBan.size()) {
                        break;
                    }
                }
            }
        }
        for (int i = 0; i < sTDataBan.size(); i++) {
            Vector vSP = new Vector();
            for (int j = 0; j < sTDataBan.get(i).length; j++) {
                vSP.add(sTDataBan.get(i)[j]);
            }
            vSP.add(Double.parseDouble(sTDataBan.get(i)[2]) * Double.parseDouble(sTDataBan.get(i)[3]));
            vTDataBan.add(vSP);
        }
        return vTDataBan;
    }

    public static String searchMaxBan(Vector<Vector> vTThongke) {
        int maxIndex = 0;
        for (int i = 1; i < vTThongke.size(); i++) {
            if (Integer.parseInt(vTThongke.get(i).get(3).toString()) > Integer.parseInt(vTThongke.get(maxIndex).get(3).toString())) {
                maxIndex = i;
            } else if (Integer.parseInt(vTThongke.get(i).get(3).toString()) == Integer.parseInt(vTThongke.get(maxIndex).get(3).toString())) {
                if (Double.parseDouble(vTThongke.get(i).get(5).toString()) > Double.parseDouble(vTThongke.get(maxIndex).get(5).toString())) {
                    maxIndex = i;
                }
            }
        }
        return vTThongke.get(maxIndex).get(0) + "|| Tên SP :" + vTThongke.get(maxIndex).get(1) + " || SL Bán:"
                + vTThongke.get(maxIndex).get(3) + vTThongke.get(maxIndex).get(4) + " || Tổng thu:" + vTThongke.get(maxIndex).get(5) + " VNĐ";
    }

    public static String searchMaxThu(Vector<Vector> vTThongke) {
        int maxIndex = 0;
        for (int i = 1; i < vTThongke.size(); i++) {
            if (Double.parseDouble(vTThongke.get(i).get(5).toString()) > Double.parseDouble(vTThongke.get(maxIndex).get(5).toString())) {
                maxIndex = i;
            } else if (Double.parseDouble(vTThongke.get(i).get(5).toString()) == Double.parseDouble(vTThongke.get(maxIndex).get(5).toString())) {
                if (Integer.parseInt(vTThongke.get(i).get(3).toString()) > Integer.parseInt(vTThongke.get(maxIndex).get(3).toString())) {
                    maxIndex = i;
                }
            }
        }
        return vTThongke.get(maxIndex).get(0) + "|| Tên SP :" + vTThongke.get(maxIndex).get(1) + " || SL Bán:"
                + vTThongke.get(maxIndex).get(3) + vTThongke.get(maxIndex).get(4) + " || Tổng thu:" + vTThongke.get(maxIndex).get(5) + " VNĐ";
//To change body of generated methods, choose Tools | Templates.
    }

    public static String tongThu(Vector<Vector> vTThongke) {
        double tongThu = 0;
        for (int i = 0; i < vTThongke.size(); i++) {
            tongThu = tongThu + Double.parseDouble(vTThongke.get(i).get(5).toString());
        }
        return tongThu + " VNĐ";
    }

}
